package gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;

import function.ComponentMover;
import function.IconGetting;

public class IconListPanel extends JPanel{
	
	/**
	 * Class: IconPanel
	 * Description: getting icon from a directory
	 * @category function
	 * @author Mr3chi
	 * @throws IOException 
	 * @since 04/05/2013
	 * 
	 */
	private static final long serialVersionUID = -5253267396862241482L;
	private final JFrame parent;
	private ArrayList<IconPanel> iconArray;
	private String dirString;
	
	public IconListPanel(final JFrame parent) {
		this.parent = parent;
		setOpaque(false);
		setLayout(null);
		iconArray = new ArrayList<IconPanel>();
		addMouseListener(new IconListPanelMouse());
	}
	
	public int getRealWidth(){
		if(iconArray == null || iconArray.size() == 0){
			return 0;
		}
		int col = this.parent.getWidth() / iconArray.get(0).getRealWidth();
		return col*iconArray.get(0).getRealWidth();
	}
	
	public int getRealHeight(){
		if(iconArray == null || iconArray.size() == 0){
			return 0;
		}
		int col = this.parent.getWidth() / iconArray.get(0).getRealWidth();
		int row = iconArray.size()/col +1; 
		return row*iconArray.get(0).getRealHeight();
		
	}
	
	public void setDirString(String dirString) throws IOException{
		this.dirString = dirString;
		iconArray.clear();
		iconArray.addAll(IconGetting.getIconsfromDirectory(this.dirString, IconGetting.ONLY_FOLDER));
		iconArray.addAll( IconGetting.getIconsfromDirectory(this.dirString, IconGetting.ONLY_FILE));
		repaintCurrentIcons();
		
	}
	
	private void drawRandomIcons(ArrayList<IconPanel> e, ComponentMover cv){
		if(e == null || e.size() == 0) return;
		int numofcolumn = this.parent.getWidth() / e.get(0).getRealWidth();
		
		int row, col;
		for(int i = 0; i < e.size(); i++){
			col = (i%numofcolumn)*e.get(i).getRealWidth();
			row = (i/numofcolumn)*e.get(i).getRealHeight();
			e.get(i).setBounds(col, row, e.get(i).getRealWidth(), e.get(i).getRealHeight());
			add(e.get(i));
			cv.registerComponent(e.get(i));
		}
		
	}
	
	public void repaintCurrentIcons(){
		ComponentMover mover = new ComponentMover();
		removeAll();
		drawRandomIcons(iconArray,mover);
	}
	
	class IconListPanelMouse extends MouseAdapter{

		@Override
		public void mouseClicked(MouseEvent e) {
			super.mouseClicked(e);
			
		}
		
	}
	
}
